package com.sky.task;

import com.alibaba.fastjson.JSON;
import com.sky.mapper.user.OrdersMapper;
import com.sky.pojo.Orders;
import com.sky.properties.WeChatProperties;
import com.sky.service.webSocket.WebSocketServer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private WebSocketServer webSocketServer;

//    @Scheduled(cron = "0/5 * * * * ? ")
    public void OrderTimeout() throws Exception {
        log.info("超时订单处理{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //查询超过15分钟的订单
        List<Orders> ordersList = ordersMapper.selectByStatus(Orders.PENDING_PAYMENT, time);
        log.info("查询超过15分钟的订单:{}",ordersList);
        //如果不为空
        if (ordersList.size()>0) {
            for (Orders orders : ordersList) {
                //查询微信接口,订单是否支付
                String jsonStr = QueryOrder(orders.getNumber());
                Map map = JSON.parseObject(jsonStr, Map.class);
                String trade_state = map.get("trade_state").toString();
                log.info("查询微信订单的状态:{}",trade_state);
                //如果支付了就更改订单状态和支付状态为已支付
                if (trade_state.equals("SUCCESS")) {
                    orders.setStatus(Orders.TO_BE_CONFIRMED);
                    orders.setPayStatus(Orders.PAID);
                    orders.setCheckoutTime(LocalDateTime.now());
                    Map<String,Object> res = new HashMap<>();
                    res.put("type",1);
                    res.put("orderId",orders.getId());
                    res.put("content","您有新订单,请及时处理");

                    String message = JSON.toJSONString(res);

                    webSocketServer.sendToAllClient(message);
                }else {
                    //没有支付,修改订单状态为已取消
                    orders.setCancelReason("订单超时,自动取消");
                    orders.setCancelTime(LocalDateTime.now());
                    orders.setStatus(Orders.CANCELLED_ORDER);
                }
                log.info("传入更新后的订单:{}",orders);
                ordersMapper.update(orders);
            }

        }

    }

    public String QueryOrder(String number) throws Exception {

        //请求URL
        URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/" + number);
        uriBuilder.setParameter("mchid", weChatProperties.getMchid());

        //完成签名并执行请求
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");
        CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                return EntityUtils.toString(response.getEntity());
            } else if (statusCode == 204) {
                return "";
            } else {
                System.out.println("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
        }
    }

}
